<template>
  <el-row>
    <!-- 头部 -->
    <el-col :span="24">
      <el-card shadow="hover">
        <el-breadcrumb :separator-icon="ArrowRightBold">
          <el-breadcrumb-item :to="{ path: '/admin_index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>订单管理</el-breadcrumb-item>
          <el-breadcrumb-item>投注订单</el-breadcrumb-item>
        </el-breadcrumb>
      </el-card>
    </el-col>
    <div style="padding: 5px;"></div>
    <!-- 内容区域 -->
    <el-col :span="24">
      <el-card shadow="hover">
        <template #header>
          <div style="margin-bottom: 10px;">
            <el-radio-group v-model="page.game_type" @change="dddd">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="aozhou">新澳门28</el-radio-button>
              <el-radio-button label="jianada">加拿大28</el-radio-button>
              <el-radio-button label="xinjiapo">澳门28</el-radio-button>
              <el-radio-button label="aomenjisu">香港28</el-radio-button>
              <el-radio-button label="yazhou">亚洲28</el-radio-button>
              <el-radio-button label="eluosi">俄罗斯28</el-radio-button>
              <el-radio-button label="xinjiapo28">新加坡28</el-radio-button>
              <el-radio-button label="ouzhou">欧洲28</el-radio-button>
              <el-radio-button label="aozhou28">澳洲28</el-radio-button>
              <el-radio-button label="moxige">墨西哥28</el-radio-button>
              <el-radio-button label="taiwan">台湾28</el-radio-button>
              <el-radio-button label="jianada28">加拿大28(自开)</el-radio-button>
              <el-radio-button label="agenting">阿根廷28</el-radio-button>
              <el-radio-button label="helan">荷兰28</el-radio-button>

              <el-radio-button label="amlhc">澳门六合彩</el-radio-button>
              <el-radio-button label="xglhc">香港六合彩</el-radio-button>
              <el-radio-button label="jslhc">极速六合彩</el-radio-button>
              <el-radio-button label="hgk3">韩国快3</el-radio-button>
              <el-radio-button label="jshgk3">韩国极速快3</el-radio-button>
<!--              <el-radio-button label="jssc">极速赛车</el-radio-button>-->
<!--              <el-radio-button label="jsft">极速飞艇</el-radio-button>-->
            </el-radio-group>
          </div>
          <div style="display: flex; align-items: center;flex-wrap: wrap;">
            <el-select   popper-class="custom-select-dropdown"    style="width: 150px;" v-model="page.status" placeholder="全部">
              <el-option label="未开奖" value="1">未开奖</el-option>
              <el-option label="已开奖" value="2">已中奖</el-option>
              <el-option label="未中奖" value="3">未中奖</el-option>
              <el-option label="已撤单" value="4">已撤单</el-option>
            </el-select>
            <div style="padding: 5px;"></div>
            <el-select   popper-class="custom-select-dropdown"   style="width: 150px;" v-model="group_id" placeholder="请选择用户分组">
              <el-option label="全部分组" value="">全部分组</el-option>
              <el-option label="未分组" value="0">未分组</el-option>
              <el-option :label="item.name" :value="item.id" v-for="item in group_list">{{ item.name }}</el-option>
            </el-select>
            <div style="padding: 5px;"></div>

            <el-date-picker v-model="page.time_date[0]" :default-value="page.time_date[0]" type="datetime" placeholder="开始日期" style="width: 180px;" />
            <div style="width: 15px"></div>
            <el-date-picker v-model="page.time_date[1]" :default-value="page.time_date[1]" default-time="12:00:00" type="datetime" placeholder="结束日期" style="width: 180px;" />
            <div style="padding: 5px;"></div>

            <div style="padding: 5px;"></div>
            <el-input style="width: 260px;" v-model="inputval" placeholder="请输入UID、手机、昵称、备注"/>

            <div style="padding: 5px;"></div>
            <el-button type="primary" :icon="Search" @click="inputSearch()" style="margin-right: 15px;">搜索</el-button>
            <div style="display: flex; justify-content: space-between;width: 100%;margin-top: 10px;">
              <div
                  style="font-size: 15px; color: #666666; font-weight: 600; background-color: #efefef; padding:6px 10px; border-radius: 5px;">
                <span style="color: red;">非中奖投注额：<span style="color: green;">￥{{ flsMoney }}</span></span>
                <span style="color: red;margin-left: 20px;">总投注金额：<span style="color: green;">￥{{ count_money }}</span></span>
                <span style="color: red;margin-left: 20px;">总中奖金额：<span style="color: green;">￥{{
                    count_amoney
                  }}</span></span>
                <span style="color: red;margin-left: 20px;">总撤单金额：<span style="color: green;">￥{{
                    chedan_money
                  }}</span></span>
              </div>
              
              <div style="display: flex;">
                <div>自动刷新开关
                <el-tooltip :content="is_auto == 1 ? '开' : '关'" placement="top">
                  <el-switch v-model="is_auto" :active-value="1" :inactive-value="0"
                             @change="openAuto">
                  </el-switch>
                </el-tooltip>
              </div>
                  <!-- <div style="display: flex;margin:0 10px;align-items: center;">速度(秒)
                    <el-input v-model="refresh_time" placeholder="请输入刷新速度" :min="2" type="number" style="width: 80px;" @input="handleRefreshTimeInput"></el-input>
                </div>
                
             
                <div style="display: flex;align-items: center;">WebSocket状态
                <el-tag :type="wsConnected ? 'success' : 'danger'" style="margin-left: 5px;">
                  {{ wsConnected ? '已连接' : '未连接' }}
                </el-tag>
              </div> -->
              </div>
            </div>
          </div>
        </template>

        <!-- 表格 -->
        <el-table :data="tableData.list" :border="true" style="width: 100%" v-loading="loading">
<!--          <el-table-column prop="id" label="序号" width="80"/>-->
          <!-- <el-table-column prop="orderid" label="订单编号" width="210" /> -->
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <!--              <div>UID：{{ scope.row.userid }}</div>-->
              <div v-if="scope.row.user?.headimgurl">
                <img :src="scope.row.user?.headimgurl" style="width: 55px;height: 55px;border-radius:50% ">
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户详情" width="150">
            <template #default="scope">
<!--              <div>UID：{{ scope.row.userid }}</div>-->
              <div style="display: flex;">

                <div>
                  <div>昵称：{{ scope.row.nickname }}</div>
                  <div>备注：{{ scope.row.user.remark }}</div>
                  <div>手机：{{scope.row.user?.phone}}</div>
<!--                  <div>类型：-->
<!--                    <el-tag type="success" v-if="scope.row.role == 0">正常玩家</el-tag>-->
<!--                    <el-tag type="danger" v-if="scope.row.role == 1">内部用户</el-tag>-->
<!--                  </div>-->
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="游戏详情" width="150" >
            <template #default="scope">
              <div v-if="scope.row.game_type=='jianada28'">加拿大28(自开)</div>
              <div v-else>{{ scope.row.game_name }}</div>
              <div>{{ scope.row.room_name }}</div>
              <div>{{ scope.row.issue }}</div>
            </template>
          </el-table-column>

          <el-table-column label="投注详情"  width="400">
            <template #default="scope">
 
              <span v-for="(order,index) in scope.row.order " :key="index" style="padding:5px 0;" >

                <span v-if="order.game_type=='jslhc' || order.game_type=='xglhc' || order.game_type=='amlhc'" >[{{order.room_betname}}/{{order.number}}/{{order.money}}]

                  <span >
<!--                <el-button type="danger"  v-if="order.status == 1" size="small" style="margin:0 5px;">未开奖</el-button>-->
                <el-button type="success" v-if="order.status == 2" size="small" style="margin:0 5px;">已中奖</el-button>
<!--                <el-button type="warning" v-if="order.status == 3" size="small" style="margin:0 5px;">未中奖</el-button>-->
                <el-button type="info" v-if="order.status == 4" size="small" style="margin:0 5px;"> 已撤单</el-button>

                <el-tag type="danger" v-if="order.status == 2">￥{{ Math.floor(order.amoney) }}</el-tag>
<!--                <el-tag type="success" v-else>￥0.00</el-tag>-->
                    </span>
                </span>
                <span v-else-if="order.game_type=='hgk3' || order.game_type=='jshgk3'">[{{order.room_betname}}{{order.number}}/{{Math.floor(order.money)}}]
                  <span >
<!--                  <el-button type="danger" v-if="order.status == 1" size="small" style="margin:0 5px;">未开奖</el-button>-->
                <el-button type="success" v-if="order.status == 2" size="small" style="margin:0 5px;">已中奖</el-button>
<!--                <el-button type="warning" v-if="order.status == 3" size="small" style="margin:0 5px;">未中奖</el-button>-->
                <el-button type="info" v-if="order.status == 4" size="small" style="margin:0 5px;">已撤单</el-button>
                <el-tag type="danger" v-if="order.status == 2" >￥{{ Math.floor(order.amoney) }}</el-tag>
<!--                <el-tag type="success" v-else>￥0.00</el-tag>-->
                  </span>
                </span>
                <span v-else>[{{order.number}}/{{Math.floor(order.money)}}]
                  <span >
<!--                  <el-button type="danger" v-if="order.status == 1" size="small" style="margin:0 5px;">未开奖</el-button>-->
                <el-button type="success" v-if="order.status == 2" size="small" style="margin:0 5px;">已中奖</el-button>
<!--                <el-button type="warning" v-if="order.status == 3" size="small" style="margin:0 5px;">未中奖</el-button>-->
                <el-button type="info" v-if="order.status == 4" size="small" style="margin:0 5px;">已撤单</el-button>
                <el-tag type="danger" v-if="order.status == 2" >￥{{ Math.floor(order.amoney) }}</el-tag>
<!--                <el-tag type="success" v-else>￥0.00</el-tag>-->
                  </span>
                </span>
              </span>
             <span v-if="scope.row.status==3" >
                <img src="/img/wzj.png" class="wzj-img">
              </span>
            </template>
          </el-table-column>

          <!-- <el-table-column prop="room_betname" label="投注类型" /> -->

          <el-table-column label="支付详情" width="200" >
            <template #default="scope">
<!--              <div>余额：-->
<!--                <el-tag type="danger">￥{{ scope.row.use_money }}</el-tag>-->
<!--              </div>-->
              <div >投注前：

                ￥{{ scope.row.bet_money_before }} /￥{{ scope.row.bet_voucher_before }}

              </div>
              <div style="padding:5px 0;">投注后：
                ￥{{ scope.row.after_money }}
                /
                ￥{{ scope.row.after_voucher }}
              </div>
<!--              <div>彩金支付：-->
<!--                <el-tag type="danger">￥{{ scope.row.voucher.toFixed(2) }}</el-tag>-->
<!--              </div>-->
            </template>
          </el-table-column>

<!--          <el-table-column label="中奖金额" width="220" >-->
<!--            <template #default="scope">-->
<!--              <div>-->
<!--                <el-tag type="danger" v-if="scope.row.status == 2">￥{{ scope.row.amoney }}</el-tag>-->
<!--                <el-tag type="success" v-else>￥0.00</el-tag>-->
<!--              </div>-->
<!--              &lt;!&ndash; <div v-if="scope.row.reward_money_after>0">中奖后：<el-tag type="danger">￥{{ scope.row.reward_money_after }}</el-tag></div> &ndash;&gt;-->
<!--            </template>-->
<!--          </el-table-column>-->

          <!-- <el-table-column label="投注方式" width="100">
              <template #default="scope">
                  <el-tag v-if="scope.row.bet_type == 1">快捷下注</el-tag>
                  <el-tag type="success" v-if="scope.row.bet_type == 2">键盘下注</el-tag>
              </template>
          </el-table-column> -->


          <el-table-column prop="issue_number" label="开奖结果" width="200"/>
          <!-- <el-table-column prop="agent_rate" label="代理费率" width="90" />
          <el-table-column prop="agent_money" label="返佣金额" width="90" /> -->
<!--          <el-table-column label="订单状态" width="100">-->
<!--            <template #default="scope">-->
<!--              <el-button type="danger" v-if="scope.row.status == 1">未开奖</el-button>-->
<!--              <el-button type="success" v-if="scope.row.status == 2">已中奖</el-button>-->
<!--              <el-button type="warning" v-if="scope.row.status == 3">未中奖</el-button>-->
<!--              <el-button type="info" v-if="scope.row.status == 4">已撤单</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column prop="create_time" label="订单时间" width="180"/>



        </el-table>
        <!-- 分页 -->

        <div style="padding: 10px;"></div>
        <div style="display: flex;">
          <el-pagination small background v-model:currentPage="page.pagenum" :page-size="page.pagesize"
                         :page-sizes="[50,100, 200]" :small="small" layout="total, sizes, prev, pager, next, jumper"
                         :total="page.total" @size-change="pageSelect" @current-change="handleCurrentChange" />

        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>

import {ref, reactive, onMounted, onUnmounted, watch} from 'vue'
import {request_post} from '@/common/axios/request.js'
import {success, error} from '@/common/tool/message.js'
import {ArrowRightBold, UserFilled, Search} from '@element-plus/icons-vue'
const loading = ref(false)
const flsMoney = ref(null)
const count_money = ref(null)
const count_amoney = ref(null)
const chedan_money = ref(null)
const group_list = ref([])
const group_id = ref('')
const refresh_time = ref(2) // 默认30秒

const tableData = reactive({list: []})
const is_auto = ref(0)
let refreshTimer = null

// WebSocket相关状态
const ws = ref(null)
const wsConnected = ref(false)

onMounted(() => {
  is_auto.value = Number(localStorage.getItem('is_auto'))||0;
  // 从localStorage加载保存的刷新速度，如果没有则使用默认值
  const savedRefreshTime = Number(localStorage.getItem('refresh_time'));
  refresh_time.value = savedRefreshTime > 0 ? savedRefreshTime : 2;
  admin_order_index()
  // 初始化自动刷新
  handleAutoRefresh()
  
  // 初始化WebSocket连接
  if(is_auto.value === 1){
    initWebSocket()
  }
  
})

// 初始化WebSocket连接
function initWebSocket() {
  // 关闭已存在的连接
  if (ws.value) {
    ws.value.close()
  }
  
  try {
    // 创建WebSocket连接
    // 使用相对路径/wsapi通过反向代理访问WebSocket
    ws.value = new WebSocket('/wsurl')
    
    // 连接建立事件
    ws.value.onopen = function() {
      console.log('WebSocket连接已建立')
      wsConnected.value = true
      
      // 发送type: admin_order_data指令
      const message = JSON.stringify({
        type: 'admin_order_request',

        game_type: page.game_type,
        status: page.status,
        group_id: page.group_id,
        time_date: page.time_date,
        uid: page.uid

      })
      ws.value.send(message)
    }
    
    // 接收消息事件
    ws.value.onmessage = function(event) {
      try {
        const data = JSON.parse(event.data)

        // 更新订单数据
        updateOrderData(data)
      } catch (e) {
        console.error('解析WebSocket数据失败:', e)
      }
    }
    
    // 连接关闭事件
    ws.value.onclose = function() {
      console.log('WebSocket连接已关闭')
      wsConnected.value = false

    }
    
    // 连接错误事件
    ws.value.onerror = function(error) {
      console.error('WebSocket连接错误:', error)
      wsConnected.value = false
    }
  } catch (e) {
    console.error('创建WebSocket连接失败:', e)
  }
}

// 更新订单数据
function updateOrderData(data) {
  // 检查数据结构是否符合admin_order_index接口返回的格式
  if (data  && data.data) {
    // 更新统计数据
    if (data.data.chedan_money !== undefined) chedan_money.value = data.data.chedan_money
    if (data.data.count_amoney !== undefined) count_amoney.value = data.data.count_amoney
    if (data.data.count_money !== undefined) count_money.value = data.data.count_money
    if (data.data.flsMoney !== undefined) flsMoney.value = data.data.flsMoney

    // 更新订单列表
    if (data.data.order_list) {
      // 如果是新数据，替换现有列表；如果是增量更新，根据实际需求处理
      tableData.list = data.data.order_list
      page.total = data.data.total
    }
    
    // 更新用户分组
    if (data.data.group_list) {
      group_list.value = data.data.group_list
    }
  }
}

onUnmounted(() => {
  // 组件卸载时清除定时器
  if(refreshTimer){
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  
  // 组件卸载时关闭WebSocket连接
  if (ws.value) {
    ws.value.close()
  }
})


function openAuto(e){
  localStorage.setItem('is_auto', e)
  is_auto.value = e
  handleAutoRefresh()
  
  // 如果关闭自动刷新，同时关闭WebSocket连接
  if (e === 0 && ws.value && ws.value.readyState === WebSocket.OPEN) {
    console.log('自动刷新关闭，关闭WebSocket连接')
    ws.value.close()
    wsConnected.value = false
  }
}

function handleAutoRefresh(){
  // 清除已有定时器
  if(refreshTimer){
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  
  // 如果自动刷新开启，设置定时器
  if(is_auto.value === 1){
    // 如果WebSocket连接未建立，尝试重新连接
    if (!wsConnected.value || !ws.value || ws.value.readyState !== WebSocket.OPEN) {
      initWebSocket()
    }
    
    // 使用refresh_time的值（秒转换为毫秒）
    const interval = refresh_time.value * 1000;
    refreshTimer = setInterval(() => {
      // 如果WebSocket连接已建立，定期发送请求保持数据更新
      if (wsConnected.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
          type: 'admin_order_request',
          // 传递当前的查询参数，确保返回的数据符合筛选条件

            game_type: page.game_type,
            status: page.status,
            group_id: page.group_id,
            time_date: page.time_date,
            uid: page.uid

        })
        ws.value.send(message)
      } else {
        // 如果WebSocket未连接，回退到API请求
        admin_order_index()
      }
    }, interval)
  } else {
    // 如果自动刷新关闭，关闭WebSocket连接
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      console.log('自动刷新关闭，关闭WebSocket连接')
      ws.value.close()
      wsConnected.value = false
    }
  }
}

// 搜索 
const inputval = ref(null)

function inputSearch() {
  page.uid = inputval.value
  loading.value = true
  
  // 如果WebSocket连接已建立，优先使用WebSocket获取数据
  if (wsConnected.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
    const message = JSON.stringify({
      type: 'admin_order_request',

        game_type: page.game_type,
        status: page.status,
        group_id: page.group_id,
        time_date: page.time_date,
        uid: page.uid,
        pagenum: page.pagenum,
        pagesize: page.pagesize

    })
    ws.value.send(message)
    // 因为WebSocket是异步的，需要手动设置loading为false
    setTimeout(() => {
      loading.value = false
    }, 500)
  } else {
    // 否则使用API请求
    admin_order_index()
  }
}

function pageSelect(val) {
  page.pagenum = 1
  page.pagesize = val
  loading.value = true
  
  // 如果WebSocket连接已建立，优先使用WebSocket获取数据
  if (wsConnected.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
    const message = JSON.stringify({
      type: 'admin_order_request',

        game_type: page.game_type,
        status: page.status,
        group_id: page.group_id,
        time_date: page.time_date,
        uid: page.uid,
        pagenum: page.pagenum,
        pagesize: page.pagesize

    })
    ws.value.send(message)
    // 因为WebSocket是异步的，需要手动设置loading为false
    setTimeout(() => {
      loading.value = false
    }, 500)
  } else {
    // 否则使用API请求
    admin_order_index()
  }
}

// 获取用户列表
function admin_order_index() {
  request_post('/admin_order_index', page).then((res) => {
    if (res.data.code == 200) {
      chedan_money.value = res.data.data.chedan_money
      count_amoney.value = res.data.data.count_amoney
      count_money.value = res.data.data.count_money
      flsMoney.value = res.data.data.flsMoney
      page.total = res.data.data.order_list.total
      tableData.list = res.data.data.order_list.data
      group_list.value = res.data.data.group_list
    } else {
      return error(res.data.msg)
    }
    loading.value = false
  })
}

var now_date = new Date();
var now_date2 = new Date();
var year = now_date.getFullYear();
var month = now_date.getMonth() + 1; // 月份从0开始，所以要加1
var day = now_date.getDate();
now_date2.setHours(0,0,0)
now_date.setHours(23, 59, 59);
const page = reactive({
  uid: '',
  game_type: 'all',
  group_id: group_id,
  time_date: [
    now_date2,
    now_date
  ],
  status: '',
  pagenum: 1,
  pagesize: 50,
  total: 0
})

function handleSizeChange(val) {
  page.pagenum = val
  loading.value = true
  admin_order_index()
}

function handleCurrentChange(val) {
  page.pagenum = val
  loading.value = true
  admin_order_index()
}

function dddd(dd) {
  page.pagenum = 1
  loading.value = true
  admin_order_index()
}

</script>

<style>
.big {
  font-size: 20px;
}

.big .el-tag {
  font-size: 16px;
}
.wzj-img{
      width: 80px;
    height: 80px;
    position: absolute;
    top: 10px;
    left: 20px;
}
</style>
